<?php
	class ListingPlan extends AppModel
	{
		var $name = "ListingPlan";
		const STATUS_ACTIVE = 1;
		const STATUS_INACTIVE = 0;
		var $fieldProperties = array(
			'plan_info' => array('fieldModifier'=>'toggleSerialized'),
		);
		var $additionalFields = array("plan_name");
		var $cacheFields = array("plan_name"=>"+4 minutes");
        var $actsAs = array();
		private $EffectivePlansCache = array();
		function afterInitialize()
		{
			$this->Plan = cri("PaidListings.Plan");
            $this->setFieldProperties("status", array("options"=>array(self::STATUS_ACTIVE =>__("Active"),self::STATUS_INACTIVE=>__("Inactive"))));
		}
		/**
		 * Return new ListingPlan Id
		 */
		function initPlanForListing($planId,$listingId,$userId =null)
		{
			$data = array('plan_id'=>$planId,'listing_id'=>$listingId,'status'=>self::STATUS_INACTIVE,'user_id'=>$userId);
            $this->create();
			$this->save(array($this->alias => $data));
			return $this->id;
		}
		/**
		 *  Create a order and transaction for a free Type ListingPlan and return order id for it.
		 */
		function orderFreePlan($listingPlanId)
		{
			$listingPlan = $this->getListingPlanInfo($listingPlanId);
			$plan = $listingPlan[$this->alias]['plan_info'];
			if($plan['Plan']['payment_type'] == Plan::PAYMENT_TRIAL)
			{
				$Order = cri("PaidListings.Order");
				$OfflinePaymentHandler = cri("PaidListings.PaymentHandler")->getPaymentHandlerObject("Offline");
				$orderId = $Order->initOrder($listingPlanId);
				$Order->recursive = -1;
				$Order->setAsCompleted($orderId);
				$orderInfo = $Order->findById($orderId);
				$Order->Transaction->createTransaction($OfflinePaymentHandler,$orderInfo,Transaction::SUCCESSFUL);
			}
			return false;
		}
		
		function getListingPlanInfo($listingPlanId)
		{
			$cacheKey = "plan_info";
			$listingPlan = GigaModelCache::read($this->alias, $listingPlanId, $cacheKey,array("duration"=>"+10 minutes"));
			if($listingPlan === false)
			{
				$listingPlan = $this->findById($listingPlanId);
				GigaModelCache::write($this->alias,$listingPlanId,$cacheKey,$listingPlan,array("duration"=>"+10 minutes"));
			}
			return $listingPlan;
		}
		function afterSave($created)
		{
			GigaModelCache::delete($this->alias, $this->id, "plan_info");
			return parent::afterSave($created);
		}
		function beforeSave($options = array())
		{
			if($this->_isNew() && isset($this->data[$this->alias]['plan_id']))
			{
				$plan = $this->Plan->getPlanInfo($this->data[$this->alias]['plan_id']);
				$this->data[$this->alias]['plan_info'] = $plan;
			}
			return parent::beforeSave($options);
		}
		function activatePlan($listingPlanId)
		{
			if(!$listingPlanId)
			{
				return;
			}
			$this->id = $listingPlanId;
			$this->saveField('status',self::STATUS_ACTIVE);
			$listingPlan = $this->getListingPlanInfo($listingPlanId);
			$EffectivePlan = $this->getEffectivePlan($listingPlan[$this->alias]['listing_id'],true);
			$EffectivePlan->implement();
		}
		/**
		 * Implement Effective created By Plans purchased by user.
		 */
		function getEffectivePlan($listingId,$refresh = false)
		{
			if(!class_exists('AbstractEffectiveListingPlan'))
			{
				App::import("Vendor","PaidListings.AbstractEffectiveListingPlan");
				App::import("Vendor","EffectiveListingPlan");	
			}
			if(!class_exists('EffectiveListingPlan'))
			{
				App::import("Vendor","PaidListings.EffectiveListingPlan");	
			}
			if($refresh || !isset($this->EffectivePlansCache[$listingId]) || !is_object($this->EffectivePlansCache[$listingId]))
			{
				$cacheKey = "active_plans";
				$EffectivePlan = null;
				if($refresh || $EffectivePlan === false ||  !is_object($EffectivePlan) || $EffectivePlan instanceof EffectiveListingPlan === false)
				{
					$activePlans = $this->find("all",array("conditions"=>array('listing_id'=>$listingId,'status'=>self::STATUS_ACTIVE)));	
					$categoryIds = cri("Listing")->field("category_list",array("Listing.id"=>$listingId));
					$EffectivePlan = new EffectiveListingPlan($listingId,$activePlans,$categoryIds);
				}
				$this->EffectivePlansCache[$listingId] =  $EffectivePlan;
			}
			return $this->EffectivePlansCache[$listingId];
		}
		
		function plan_name($listingPlan)
		{
			$planTitle = false;
			if(isset($listingPlan[$this->alias]['listing_id']) && is_array($listingPlan[$this->alias]['plan_info']))
			{
				$title = cri("Listing")->field("title",array("Listing.id"=>$listingPlan[$this->alias]['listing_id']));
				$planTitle = $listingPlan[$this->alias]['plan_info']['Plan']['title'];
				$planTitle = String::insert(__(":planName for :listingName"),array("planName"=>$planTitle,'listingName'=>$title));
			}
			return $planTitle;
		}
		
		function hasAnyListing($userId)
		{
			return $this->hasAny(array("user_id"=>$userId));
		}
        
        function showUserInfo()
        {
          $this->Behaviors->attach('Users.UserContent' , array(
							'badwordFilter' => true, 
							'fieldsToFilter' => array('title','description'),
							'posterModels'=>array('Users.User'=>array('dependent'=>true))	
					));
        }
	}
?>